package edu.wfu.preparedDishes.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.wfu.preparedDishes.common.utils.PageUtils;
import edu.wfu.preparedDishes.common.utils.Query;
import edu.wfu.preparedDishes.user.dao.UserDao;
import edu.wfu.preparedDishes.user.entity.UserEntity;
import edu.wfu.preparedDishes.user.service.Code2SessionService;
import edu.wfu.preparedDishes.user.service.UserService;
import edu.wfu.preparedDishes.user.utils.UUIDUtil;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Slf4j
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
    @Resource
    private Code2SessionService code2SessionService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                new QueryWrapper<UserEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public UserEntity getUser(String openId){
        return this.baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("open_id", openId));
    }
    /**
     * 登录
     * @param code
     * @return token
     */
    @Override
    public String addUser(String code) {
        ResponseEntity<Code2SessionService.ResultData> sessionInfo = code2SessionService.getSessionInfo(code);
        Code2SessionService.ResultData body = sessionInfo.getBody();
        String openid = body.getOpenid();
        UserEntity userEntity1 = this.baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("open_id", openid));
        if(userEntity1==null){
            UserEntity userEntity= new UserEntity().
                    setOpenId(openid).
                    setUserRole(1).
                    setUserName(UUIDUtil.get12UUID());
            //将userEntity里的openid和username插入数据库
            this.baseMapper.insert(userEntity);
        }
        String key="7122";
        Map<String,Object> claims=new HashMap<>();
        claims.put("userId",userEntity1.getUserId());
        String token = Jwts.builder().setClaims(claims).setSubject(openid).signWith(SignatureAlgorithm.HS512, key).compact();
        String subject = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody().getSubject();
        System.out.println(subject);
        Object userId = claims.get("userId");
        System.out.println(userId);
        return token;
    }

}